<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/17 23:28
 */

namespace module\user\model;

use mof\interface\UserInterface;
use mof\Model;

/**
 * 用户模型
 * @property int $id
 * @property string $username
 * @property string $mobile
 * @property string $nickname
 * @property string $avatar
 * @property string $password
 * @property int $vip
 * @property string $vip_expire
 * @property int $score
 * @property int $status
 * @property string $create_at
 * @property string $login_at
 */
class User extends Model implements UserInterface
{
    protected $name       = 'user';
    protected $updateTime = false;

    protected $hidden = ['password'];

    protected $type = [
        'avatar' => 'storage',
        'score'  => 'integer',
    ];

    protected $append = [
        'vip_day'
    ];

    protected array $searchFields = [
        'id'        => 'integer',
        'username'  => ['type' => 'string', 'op' => 'like'],
        'mobile'    => 'string',
        'vip'       => ['integer', 'zero' => true],
        'status'    => ['integer', 'zero' => true],
        'create_at' => ['datetime', 'op' => 'between'],
    ];

    public function getUserType(): string
    {
        return 'user';
    }

    public function getId(): int
    {
        return $this->getAttr('id');
    }

    public function getNickName(): string
    {
        return $this->getAttr('nickname');
    }

    public function getAvatar(): string
    {
        return $this->getAttr('avatar');
    }

    protected function getIsVipAttr($value, $data): bool
    {
        return $this->getAttr('vip') > 0 && $this->getAttr('vip_day') > 0;
    }

    protected function getVipDayAttr($value, $data): int
    {
        if (isset($data['vip_expire'])) {
            $expireAt = $this->getAttr('vip_expire');
            return $expireAt ? ceil((strtotime($expireAt) - time()) / 86400) : 0;
        }
        return 0;
    }

    /**
     * 密码hash，hash后为60个字符
     * @param $value
     * @return string
     */
    public function setPasswordAttr($value): string
    {
        return $value ? password_hash($value, PASSWORD_BCRYPT) : '';
    }

    public function __construct(object|array $data = [])
    {
        parent::__construct($data);
    }


}